import { createRouter, createWebHistory } from 'vue-router'
import Home from '@/views/Home.vue'
import BackApp from '@/views/BackApp.vue'
import store from '@/store'
const routes = [
  {
    path: '/',
    component: BackApp,
    children: [
      {
        path: '',
        name: 'Home',
        component: Home,
        meta: {
          full: true,
          noFooter: true
        }
      },
      {
        path: '/about',
        name: 'About',
        meta: {
          title: '关于'
        },
        component: () => import(/* webpackChunkName: "about" */ '@/views/About.vue')
      },
      {
        path: '/login',
        name: 'Login',
        meta: {
          title: '登陆'
        },
        component: () => import(/* webpackChunkName: "login" */ '@/views/Login.vue')
      },
      {
        path: '/my_apps',
        name: 'MyApps',
        meta: {
          title: '我的App',
          requireLogin: true
        },
        component: () => import(/* webpackChunkName: "my_apps" */ '@/views/MyApps.vue'),
        children: [
          {
            path: '',
            component: () => import(/* webpackChunkName: "my_apps" */ '@/views/MyAppList.vue')
          },
          {
            path: ':Platform/:PackageName',
            meta: {
              title: 'App详情'
            },
            component: () => import(/* webpackChunkName: "app_detail" */ '@/views/AppDetail.vue')
          }
        ]
      },
      {
        path: '/:notFound*',
        name: 'NotFound',
        component: () => import(/* webpackChunkName: "notFound" */ '@/views/NotFound.vue')
      }
    ]
  },
  {
    path: '/download/:ID',
    name: 'Download',
    component: () => import(/* webpackChunkName: "download" */ '@/views/AppDownload.vue')
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

router.beforeEach(function (to, from, next) {
  // 如果目标页面时登陆页面，但是已有保存的Token，说明已经登陆，跳转首页
  if (to.fullPath === '/login' && store.state.token != null) {
    next('/')
    return
  }
  // 如果目标路由要求登陆，而没有已保存的Token则跳转到登陆页面
  if (to.meta && to.meta.requireLogin && store.state.token == null) {
    next('/login')
    return
  }

  document.title = 'App Box' + (to.meta.title ? ` - ${to.meta.title}` : '')

  next()
}
)
export default router
